# Name: JoinUrbanGrid.py - MCBS 10/20/2014
# Description: Joins Urban areas to grid and saves table

# import system module
import arcpy
from arcpy import env
#from arcpy.sa import *


# Set workspace environment:
#env.workspace = "CanasatData.gdb"
env.workspace = "C:\Users\Marcelo\Documents\Sugarcane\Offline Data\MunicBasedData\CanasatData.gdb"
env.overwriteOutput = True
#arcpy.CheckOutExtension("Spatial")

# Folder to store tables:
PathForTables = "C:\Users\Marcelo\Documents\Sugarcane\Offline Data\MunicBasedData\Tables"

# Input grid:
GridName      = "G1kmMiR"
# Output grids name:
OutName       = "CSG1k40kmUrban"

JoinClass       = "UrbanAreas" 
OutputFeature   = OutName
fieldmappings   = arcpy.FieldMappings()
fieldmappings.addTable(GridName)
arcpy.SpatialJoin_analysis(GridName, JoinClass, OutputFeature,
						   "JOIN_ONE_TO_MANY", "KEEP_ALL", fieldmappings,
						   "COMPLETELY_WITHIN", "", "")
print "Joining attributes from " + JoinClass + " to grid."
print "New Grid file containing attributes created: " + OutputFeature
print " "
# Save .dbf tables in specified folder
TableName    = OutputFeature + ".dbf"
arcpy.TableToTable_conversion(OutputFeature, PathForTables, TableName)

